<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useProductStore } from '@/stores/product'
import ProductCard from '@/components/ProductCard.vue'

const product = useProductStore()
const pageNo = ref(1)
const pageSize = ref(12)
const current = ref<number | undefined>(undefined)

onMounted(async () => {
  await product.fetchCategories()
  await product.fetchProducts({ pageNo: pageNo.value, pageSize: pageSize.value, categoryId: current.value })
})

async function select(id?: number) {
  current.value = id
  await product.fetchProducts({ pageNo: 1, pageSize: pageSize.value, categoryId: current.value })
}
</script>

<template>
  <div class="container">
    <aside class="side">
      <button :class="{ active: !current }" @click="select()">全部分类</button>
      <button v-for="c in product.categories" :key="c.id" :class="{ active: current === c.id }" @click="select(c.id)">{{ c.name }}</button>
    </aside>
    <main class="main">
      <div class="grid">
        <ProductCard v-for="p in product.products" :key="p.id" :item="p" />
      </div>
    </main>
  </div>
</template>

<style scoped>
.container { display: grid; grid-template-columns: 240px 1fr; gap: 16px; padding: 16px; }
.side { display: flex; flex-direction: column; gap: 8px; }
.side button { text-align: left; padding: 8px 10px; border: 1px solid #eee; border-radius: 6px; background: #fff; }
.side button.active { background: #42b883; color: #fff; border-color: #42b883; }
.grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; }
@media (max-width: 960px){ .container { grid-template-columns: 1fr; } .grid { grid-template-columns: repeat(2, 1fr); } }
</style>